<template>
  <el-card :style="{'width':'100%'}">
    <el-row>
      <el-avatar :src="item.userAvatar" :style="{'margin-right':'15px'}"/>
      <el-col :span="22">
        <el-row>
          {{ item.userName }} <span v-if="item.replyName !== ''">&nbsp;回复&nbsp;{{ item.replyName }}</span>
        </el-row>
        <el-row>
          <small>{{ GMTToStr(item.createTime) }}</small>
          <small :style="{'position':'absolute','right':0}" @click.prevent="showComment = !showComment">回复</small>
        </el-row>
      </el-col>
    </el-row>
    <el-row :style="{'margin':'15px 0'}">
      {{ item.content }}
    </el-row>
    <el-row v-if="showComment">
      <el-form v-model="commentVal" :style="{'width':'100%'}">
        <el-form-item :style="{'width':'100%'}">
          <el-input type="textarea" v-model="commentVal" showCount :maxlength="100"/>
        </el-form-item>
        <el-form-item :style="{'width':'100%','text-align':'right'}">
          <el-button type="primary" @click.prevent="publishComment">
            评论
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row :style="{'margin':'0 5%' }">
      <slot></slot>
    </el-row>
  </el-card>

</template>

<script>
import { defineComponent, reactive, ref } from 'vue'
import { insertComment } from '@/api/comment'
import { ElMessage } from 'element-plus'
import { GMTToStr } from '@/utils/date'

export default defineComponent({
  name: 'Comment',
  props: {
    item: {}
  },
  setup (props, { emit }) {
    const comment = reactive(props.item)
    const showComment = ref(false)
    const commentVal = ref('')
    const publishComment = async () => {
      if (!props.item) {
        return
      }
      let parentId = props.item.parentId

      // eslint-disable-next-line eqeqeq
      if (props.item.parentId === 0) {
        parentId = props.item.id
      }
      const reply = await insertComment({
        content: commentVal.value,
        replyID: props.item.userID,
        replyName: props.item.userName,
        replyAvatar: props.item.userAvatar,
        parentId: parentId,
        articleId: props.item.articleId
      })
      if (reply.data.code === 0) {
        ElMessage({
          message: '发布成功',
          type: 'success',
          offset: 90,
          duration: 1500
        })
        emit('refreshComment')
        return
      }
      ElMessage({
        message: reply.data.msg,
        type: 'error',
        offset: 90,
        duration: 1500
      })
    }

    return {
      showComment,
      comment,
      commentVal,
      publishComment,
      GMTToStr
    }
  }
})
</script>

<style scoped>

</style>
